package com.hfh.main.model;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hfh.main.common.annotate.JwtToken;
import com.hfh.main.common.resp.Result;
import com.hfh.main.common.utils.ZhiPuUtil;
import com.hfh.main.matrix.entity.WeekMatrixEntity;
import com.hfh.main.matrix.entity.WeekMatrixEnum;
import com.hfh.main.matrix.service.WeekMatrixService;
import com.hfh.main.report.entity.DailyReportEntity;
import com.hfh.main.report.service.DailyReportService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.util.List;

@Tag(name = "模型")
@RestController
@RequestMapping("/model")
public class ModelController {

    private static final Logger log = LoggerFactory.getLogger(ModelController.class);
    @Autowired
    private DailyReportService dailyReportService;
    @Autowired
    private WeekMatrixService weekMatrixService;

    // 创建DecimalFormat对象，并设置格式为保留两位小数
    private DecimalFormat df = new DecimalFormat("#.##");

    @JwtToken
    @Operation(summary = "纯调用")
    @PostMapping("/generalAnalytical/{param}")
    public Result<?> generalAnalytical(@PathVariable @Validated String param) {
        String invokeMsg = ZhiPuUtil.invoke(param);
        return Result.success(invokeMsg);
    }

    @JwtToken
    @Operation(summary = "手动触发-根据学号对日报进行总结")
    @PostMapping("/generalConclude/{param}")
    public Result<?> generalConclude(@PathVariable @Validated String param) {
        LambdaQueryWrapper<DailyReportEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DailyReportEntity::getAcc, param);
        List<DailyReportEntity> list = dailyReportService.list(wrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            List<DailyReportEntity> collect = list.stream().filter(f -> StringUtils.isNotEmpty(f.getReport()) && StringUtils.isEmpty(f.getConclude())).toList();
            //进行调用
            for (DailyReportEntity c : collect) {
                String report = c.getReport();
                String requestStr = ModelPrompt.dailyReport + report;
                String msg = ZhiPuUtil.invoke(requestStr);
                log.info("模型调用 提示词为 {} , 返回为 {}", requestStr, msg);
                c.setConclude(msg);
                dailyReportService.updateById(c);
            }
            log.info("模型调用 本次调用完成 {} ", param);
        }
        String invokeMsg = ZhiPuUtil.invoke(param);
        return Result.success(invokeMsg);
    }


    @JwtToken
    @Operation(summary = "手动触发-根据学号对周报进行总结")
    @PostMapping("/generalWeekConclude/{param}")
    public Result<?> generalWeekConclude(@PathVariable @Validated String param) {
        LambdaQueryWrapper<WeekMatrixEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WeekMatrixEntity::getAcc, param);
        List<WeekMatrixEntity> list = weekMatrixService.list(wrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            //进行调用
            for (WeekMatrixEntity c : list) {
                LambdaQueryWrapper<DailyReportEntity> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.eq(DailyReportEntity::getAcc, param);
                if (c.getWeekNumber() == 1) {
                    wrapper2.between(DailyReportEntity::getDate, "2024-07-01", "2024-07-07");
                }
                if (c.getWeekNumber() == 2) {
                    wrapper2.between(DailyReportEntity::getDate, "2024-07-08", "2024-07-14");
                }
                List<DailyReportEntity> result = dailyReportService.list(wrapper2);
                StringBuilder merge = new StringBuilder();
                for (DailyReportEntity d : result) {
                    merge.append(d.getConclude()).append("\r\n");
                }
                String identity = c.getIdentity();
                WeekMatrixEnum e = WeekMatrixEnum.of(identity);
                String format = String.format(ModelPrompt.weekReport, e.getMatrix1Name(), e.getMatrix2Name(), e.getMatrix3Name(), e.getMatrix4Name(), e.getMatrix5Name());
                String requestStr = format + merge.toString();
                String msg = ZhiPuUtil.invoke(requestStr);
                c.setContent(msg);
                weekMatrixService.updateById(c);
            }
            log.info("模型调用 本次调用完成 {} ", param);
        }
        String invokeMsg = ZhiPuUtil.invoke(param);
        return Result.success(invokeMsg);
    }


    @JwtToken
    @Operation(summary = "手动触发-算平均分")
    @PostMapping("/generalAverage")
    public Result<?> generalAverage() {
        LambdaQueryWrapper<WeekMatrixEntity> wrapper = new LambdaQueryWrapper<>();
        List<WeekMatrixEntity> list = weekMatrixService.list(wrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            //进行调用
            for (WeekMatrixEntity c : list) {
                double matrix1Score = c.getMatrix1Score();
                double matrix2Score = c.getMatrix2Score();
                double matrix3Score = c.getMatrix3Score();
                double matrix4Score = c.getMatrix4Score();
                double average = (matrix1Score + matrix2Score + matrix3Score + matrix4Score) / 4;

                // 格式化数字
                String formattedValue = df.format(average);

                c.setWeekScore(Double.parseDouble(formattedValue));
                weekMatrixService.updateById(c);
            }
            log.info("======计算完成======");
        }
        return Result.success();
    }
}
